/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2023-2023. All rights reserved.
 *
 */

import { InputFile, InputFiles } from '@ohos/hvigor';
import * as fse from 'fs-extra';

import { CommonConst, DefaultTargetConst } from '../const/common-const.js';
import { TargetSourceSetModel } from '../model/source-set/source-set-model.js';
import { ModuleBuildProfile } from '../options/build/module-build-profile.js';
import { AbstractGenerateMetadata } from './abstract/abstract-generate-metadata.js';
import { TaskNames } from './common/task-names.js';
import { ModuleTargetData } from './data/hap-task-target-data.js';
import { GlobalProjectDataService } from './service/global-project-data-service.js';
import { TargetTaskService } from './service/target-task-service.js';
import { SignModuleRemoteHsp } from './sign-module-remote-hsp.js';

import Task = TaskNames.Task;

/**
 * Generate OutputMetadata Task
 */
export class GenerateMetadata extends AbstractGenerateMetadata {
  private _hspDepsTarget: Map<string, string> = new Map();

  constructor(targetService: TargetTaskService) {
    super(targetService, Task.GENERATE_METADATA);
  }

  @InputFile() private get jsonPath(): string {
    const sourceSetModel = this.sourceSetModel as TargetSourceSetModel;
    return sourceSetModel.getModuleTargetRes().getJsonPath();
  }

  @InputFiles() private get relatedEntryJsonList(): string[] {
    return this.getRelatedEntryJsonList(CommonConst.MODULE_JSON5);
  }

  protected initTaskDependsForOtherModule() {
    this.service.getHspModuleDependencyNames().forEach((hspName) => {
      for (const target of [this.targetData.getTargetName(), DefaultTargetConst.DEFAULT_TARGET]) {
        const hspTargetData = this.targetData.findTargetDataByName(hspName, target);
        if (hspTargetData === undefined) {
          continue;
        }
        const taskName = `${hspTargetData.getTargetName() ?? DefaultTargetConst.DEFAULT_TARGET}@${Task.GENERATE_METADATA.name!}`;
        const hspTask = this.node.findModuleByName(hspName)?.getTaskByName(taskName);
        if (hspTask) {
          this._hspDepsTarget.set(hspName, hspTargetData?.getTargetName() ?? DefaultTargetConst.DEFAULT_TARGET);
          this.declareDepends(taskName, hspName);
          return;
        }
      }
    });
  }

  protected getDistroFilterObj(relatedEntryTargetData: ModuleTargetData): ModuleBuildProfile.DistroFilterBuildOpt | undefined {
    return relatedEntryTargetData?.getTargetOpt().config?.distroFilter ?? undefined;
  }

  initTaskDepends() {
    const projectOhpmPath = this.service.getProjectModel().getRemoteHspPath();
    const moduleOhpmPath = this.moduleModel.getRemoteHspPath();

    // 判断当前target对应的module是否已经存在模块级remoteHsp签名任务
    const moduleRemoteHspSet: Set<string> = GlobalProjectDataService.getInstance().getModuleRemoteHspPromise();
    const ifHasModuleTask = moduleRemoteHspSet.has(this.moduleName);

    // 判断是否存在工程级与模块级的remoteHsp文件，如果没有则不执行SignModuleRemoteHsp任务
    if (fse.existsSync(projectOhpmPath) || fse.existsSync(moduleOhpmPath)) {
      // 如果当前target对应的module存在模块级remoteHsp签名任务则不再过多依赖避免重复签名
      if (!ifHasModuleTask) {
        GlobalProjectDataService.getInstance().setModuleRemoteHspPromise(this.moduleName);
        this.dependsOn(`${this.targetData.getTargetName()}@${SignModuleRemoteHsp.name}`);
      }
    }
  }
}
